<?php

// $Id$

require_once(TANGRA_MAIN_DIR.'interfaces/i_db_storable.class.php');


require_once('tcms_content_publish.class.php');


class TCMS_Content_Publish_Up_DBC extends TCMS_Content_Publish implements I_DB_Storable {
	public function save(DB_Connection $dbc) {
		$ret = false;

		if ($this->get_id()) {
			$ret = $this->update($dbc);
		} else {
			$ret = $this->insert($dbc);
			$this->set_id($ret);
		}

		return $ret;
	}



	public function load_by_id(DB_Connection $dbc, $id) {
		tangra_if_not_int_throw_e($id);

		$ret = false;

		$sql = "select content, publish_up, processed from tcms_content_publish_up where id = $id";
		$rez = $dbc->execute($sql);

		if (!$rez->is_eof()) {
			$rez_obj = $rez->fetch_object();

			$this->set_id($id);
			$this->set_content($rez_obj->ARTICLE);
			$this->set_publish_up($rez_obj->PUBLISH_UP);
			$this->set_processed($rez_obj->PROCESSED);

			$ret = $id;
		}

		return $ret;
	}


	protected function insert(DB_Connection $dbc) {
		$ret = false;

		$id = $dbc->generate_id('tcms_content_publish_up_seq');
		$content = $this->get_content();
		$publish_up = $this->get_publish_up();
		$processed = $this->get_processed() ? 1 : 0;

		if ($id) {
			$sql = "insert into tcms_content_publish_up (id, ".
									      "content, ".
									      "publish_up, ".
									      "processed ".
									      ") ".
								"values ".
									      "($id,".
									      "$content, ".
									      "'$publish_up', ".
									      "$processed ".
									      ")";
			$dbc->execute($sql);
			$ret = $id;
		} else {
			throw new TE_Exception('tcms_content_publish_up_seq');
		}

		return $ret;
	}


	protected function update(DB_Connection $dbc) {
		$id = $this->get_id();

		$content = $this->get_content();
		$publish_up = $this->get_publish_up();
		$processed = $this->get_processed() ? 1 : 0;

		$sql = "update tcms_content_publish_up set ".
						"content = $content, ".
						"publish_up = '$publish_up', ".
						"processed = $processed ".
					"where id = ".$id;

		$dbc->execute($sql);
		$ret = $id;

		return $ret;
	}


	public static function delete(DB_Connection $dbc, $id) {
		tangra_if_not_int_throw_e($id);

		$sql = "delete from tcms_content_publish_up where id = $id";
		$dbc->execute($sql);
	}


	public function load_by_content(DB_Connection $dbc, $content_id) {
		tangra_if_not_int_throw_e($content_id);

		$ret = false;

		$sql = "select id from tcms_content_publish_up where content = $content_id";

		$rez = $dbc->execute($sql);
		if (!$rez->is_eod()) {
			$rez_obj = $rez->fetch_object();
			$ret = $this->load_by_id($dbc, $content_id);
		}
	}


	public static function update_processed(DB_Connection $dbc, $id) {
		tangra_if_not_int_throw_e($id);

		$sql = "update tcms_content_publish_up set processed = 1 where id = $id";
		$dbc->execute($sql);
	}


	public static function remove_all_processed($dbc) {
		$sql = "delete from tcms_content_publish_up processed = 1";
		$dbc->execute($sql);
	}
}